#include <string.h>
#include "..\inc\def.h"
#include "..\inc\44b.h"
#include "..\inc\44blib.h"
#include "..\inc\tp.h"

#define LOOP 1000
volatile unsigned char  adcend=0;

void __irq Adc_or_TsSep(void);

void __irq Adc_or_TsSep(void)
{
    int i;
     U32 Pt[6];
     rI_ISPC=BIT_EINT4567;	//clear pending_bit
	 rEXTINTPND=0xf;
	//TSPX(GPE3) TSMX(GPE4)  TSPY(GPE6) TSMY(GPE7) 
        //  0		1	       1          0
	rPDATE=rPDATE&(~(0x01<<7))|(0x01<<6);
    rPDATE=rPDATE&(~(0x01<<3))|(0x01<<4);
	// <X-Position Read>
	rADCCON=0x1<<2;			// AIN1
	
	for(i=0;i<LOOP;i++);		//delay to set up the next channel
	for(i=0;i<5;i++)
	{
    	    rADCCON|=0x1;		// Start X-position conversion
	    while(rADCCON & 0x1);	// Check if Enable_start is low
    	    while(!(rADCCON & 0x40));	// Check ECFLG
	    Pt[i]=(0x3ff&rADCDAT);
	}
	Pt[5]=(Pt[0]+Pt[1]+Pt[2]+Pt[3]+Pt[4])/5;
	Uart_Printf("X-Posion[AIN1] is %04d\n", Pt[5]);
	
	
    rPDATE=rPDATE&(~(0x01<<6))|(0x01<<7);
    rPDATE=rPDATE&(~(0x01<<4))|(0x01<<3);
	rADCCON=0x0<<2;			// AIN0
	for(i=0;i<5;i++)
	{
    	    rADCCON|=0x1;		// Start X-position conversion
	    while(rADCCON & 0x1);	// Check if Enable_start is low
    	    while(!(rADCCON & 0x40));	// Check ECFLG
	    Pt[i]=(0x3ff&rADCDAT);
	}
	Pt[5]=(Pt[0]+Pt[1]+Pt[2]+Pt[3]+Pt[4])/5;
	Uart_Printf("Y-Posion[AIN0] is %04d\n", Pt[5]);
	    
    	adcend=1;
    	for(i=0;i<LOOP;i++);		//delay to set up the next channel
    	rPDATE=rPDATE|(0x03<<6);
        rPDATE=rPDATE&(~(0x01<<4))|(0x01<<3);
    	for(i=0;i<LOOP;i++);		//delay to set up the next channel
    	
    	
    	
}

void Ts_Sep(void)
{
     int i;
    
    //TSPX(GPE3) TSMX(GPE4)  TSPY(GPE6) TSMY(GPE7) 
        //  0		1	       1          0
	rPDATE=rPDATE|(0x03<<6);
    rPDATE=rPDATE&(~(0x01<<4))|(0x01<<3);
    for(i=0;i<LOOP;i++);		//delay to set up the next channel
    Uart_Printf("[Touch Screen Test.]\n");
    Uart_Printf("Separate X/Y position conversion mode test\n");
    Uart_Printf("\nType any key to exit!!!\n");
    Uart_Printf("\nStylus Down, please...... \n");
    
    rEXTINT=0x0;//0x22222222;
    rINTCON=0x5;
    pISR_EINT4567=(int)Adc_or_TsSep;
    
    rCLKCON=0x7ff8;
    rADCPSR=0x4;
    rINTMSK=~(BIT_GLOBAL|BIT_EINT4567);
    Uart_Printf("[Touch Screen Test]\n");
    
    Uart_Getch();
    rINTMSK |=BIT_GLOBAL|BIT_EINT4567;
    Uart_Printf("[Touch Screen Test Over]\n");
    
}

